// pages/chat/chat.js

const request = require('../../utils/request.js');
const msgcallback = require('../../utils/msgcallback.js');
Page({
  data: {
    from_info: [],
    from_id:0,
    my_info: [],
    content: '',
    content_list: [],
    scroll_top:11110
  },
  onLoad: function(options) {
    var id = options.id
    this.setData({
      from_id: options.id,
      my_info: getApp().globalData.userInfo
    })
    let _this = this
    request.requests('userInfo', {
      id
    }, 'get', function(data) {
      console.log(data)
      _this.setData({
        from_info: data.result,
      })
      wx.setNavigationBarTitle({
        title: data.result.name
      })
      _this.get_msg(_this)
    });
    
  },
  onShow: function() {
    var _this = this
    msgcallback.msgcallback(_this.data.from_id, _this.data.my_info.id);
    wx.onSocketMessage(function(data) {
      console.log(data.data)
      var msg = JSON.parse(data.data)
      switch (msg['type']) {
        case 'msg':
          _this.data.content_list.push(msg)
          _this.setData({
            content: '',
            content_list: _this.data.content_list,
            scroll_top: (_this.data.content_list + 1).length * 1000
          })
          msgcallback.msgcallback(_this.data.from_info.id, _this.data.my_info.id);
          break;
      }

    })
  },
  get_msg: function (_this){
   
    console.log('data',_this.data)
    request.requests('messageList', {
      from_id: _this.data.from_info.id,
      send_id: _this.data.my_info.id
    }, 'get', function (data) {
      console.log(data)
      _this.setData({
        content_list: data.result,
        scroll_top: data.result.length*1000
      })
    });
  },
  

  content_add: function(opt) {
    this.setData({
      content: opt.detail.value
    })
  },
  sendClick: function() {
    let _this = this
    console.log('我要发送消息啦')
    wx.sendSocketMessage({
      data: JSON.stringify({
        type: 'msg',
        from_id: _this.data.my_info.id,
        from_name: _this.data.my_info.name,
        from_img: _this.data.my_info.img,
        send_id: _this.data.from_info.id,
        send_name: _this.data.from_info.name,
        send_img: _this.data.from_info.img,
        content: _this.data.content,
        msg_type: 1
      }),
      success() {
        _this.data.content_list.push({
          type: 'msg',
          from_id: _this.data.my_info.id,
          send_id: _this.data.from_info.id,
          content: _this.data.content,
          msg_type: 1
        })
        _this.setData({
          content: '',
          content_list: _this.data.content_list,
          scroll_top: (_this.data.content_list+1).length * 1000
        })
      }
    })

  }
})